import React, { PureComponent } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {Row,Col,Card,Form,Input,Select,Icon,Button,Dropdown,Menu,InputNumber,DatePicker,Modal,message,Tree,TreeSelect,Badge,Divider,Upload,Radio,label,Table,Popconfirm ,TimePicker} from 'antd';
import StandardTable from '../../components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from '../Mana/Role.less';  

/*用户中心-用户管理*/
const { MonthPicker, RangePicker } = DatePicker;
const FormItem = Form.Item;
const Option = Select.Option;
var school_select=[];/*学校*/
var treeData =[];/*tree  机构 data*/
var userId="";
var headerimg="";
var imageUrl="";
const getValue = obj =>Object.keys(obj).map(key => obj[key]).join(',');

const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible,title,obj} = props;
  const {getFieldDecorator} = form;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      	if(fieldsValue.name == undefined) {	fieldsValue.name = ""}
				if(fieldsValue.phone == undefined) {	fieldsValue.phone = ""}
				if(fieldsValue.loginAccount == undefined) {	fieldsValue.loginAccount = ""}
				if(fieldsValue.email == undefined) {	fieldsValue.email = ""}
				if(fieldsValue.state == undefined) {	fieldsValue.state = 1}
				fieldsValue.headPortrait=headerimg;
				fieldsValue.inJobDate=moment(fieldsValue.inJobDate).format('YYYY/MM/DD');
				fieldsValue.outJobDate=moment(fieldsValue.outJobDate).format('YYYY/MM/DD');
	      form.resetFields();
	      handleAdd(title,obj.userId,fieldsValue);
    });
  };
  	return(
			<Modal
				maskClosable={false}
				destroyOnClose={true}
		        visible={modalVisible}
		        title={title}
		        width={'30%'}
		        okText="确定"
		        onCancel={() => handleModalVisible(false,'','')}
		        onOk={okHandle}
		      >
	        <Form layout="horizontal">
	        	<FormItem label="添加立方币" labelCol={{span: 7}}  wrapperCol={{span: 15}}>
		            {getFieldDecorator('lfb', {
		              rules: [{ required: true, message: '立方币不能为空!' }],
		            })(
		              <Input placeholder="请输入" />
		            )}
	          	</FormItem>
	        </Form>
      		</Modal>
		);
});

@connect(({ userCenterUser, loading,menu }) => ({
  userCenterUser,
  loading: loading.models.userCenterUser,
  threeMenu: menu.threeMenu,
}))
@Form.create()
export default class TableList extends PureComponent {
	state = {
	    modalVisible: false,
	    selectedRows: [],
	    formValues: {},
	    obj: "",
	};
  componentDidMount() {
  	/*按钮查询*/
		this.props.dispatch({	type: 'menu/fetch_three_menu',});
  	/*默认查询table 数据*/
		this.props.dispatch({type: 'userCenterUser/fetch_centeruser',});
		/*默认查询组织机构  tree*/
		this.props.dispatch({
			type: 'userCenterUser/fetch_organ_tree',
			callback: (res,data) => {
				treeData=[];
				if(res==1){
					treeData=data;
				}
	    },
		});
		/*默认查询 学校 select */
		this.props.dispatch({
			type: 'userCenterUser/fetch_ListByschoolselect',
			callback: (res,data) => {
				school_select=[];
				for (let i = 0; i < data.length; i++) {
				  school_select.push(<Option key={data[i].id}>{data[i].value}</Option>);
				}
			}
		});
  }

	handleStandardTableChange = (pagination, filtersArg, sorter) => {
	    const { dispatch } = this.props;
	    const { formValues } = this.state;
	    const filters = Object.keys(filtersArg).reduce((obj, key) => {
	    const newObj = { ...obj };
	      newObj[key] = getValue(filtersArg[key]);
	      return newObj;
	    }, {});
	    const params = {
	      currentPage: pagination.current,
	      pageSize: pagination.pageSize,
	      ...formValues,
	      ...filters,
	    };
	    if (sorter.field) {
	      params.sorter = `${sorter.field}_${sorter.order}`;
	    }
	    dispatch({
	      type: 'userCenterUser/fetch_centeruser',
	      payload: params,
	    });
	};
	handleSelectRows = rows => {
	    this.setState({
	      selectedRows: rows,
	    });
	};
	/*重置*/
	handleFormReset = () => {
		const {	form,	dispatch} = this.props;
		form.resetFields();
		this.setState({	formValues: {},});
		dispatch({type: 'userCenterUser/fetch_centeruser',});
	}
	/*查询*/
	handleSearch = e => {
	    e.preventDefault();
	    const { dispatch, form } = this.props;
	    form.validateFields((err, fieldsValue) => {
		    if (err) return;
		    const values = {  ...fieldsValue,};
		    this.setState({ formValues: values,});
		 	 	if(values.name == undefined) {	values.name = ""}
				if(values.phone == undefined) {	values.phone = ""}
				if(values.address == undefined) {	values.address = ""}
				if(values.state == undefined) {	values.state = ""}
        dispatch({
	        type: 'userCenterUser/fetch_centeruser',
	        payload:{...values},
        });
	    });
	};
	/*弹窗*/
  handleModalVisible = (flag,record,title) => {
  	console.log(record)
  	userId=record.userId;
  	console.log(title)
	  	if(flag==false){
	  		this.setState({
		      modalVisible: false,
		    });
	  	}else{
	  		var obj={};
		    this.setState({
		      modalVisible: !!flag,
		      title: title,
		      obj: obj,
		    });
	  	}
  	};
	/*新增,修改*/
	handleAdd = (title,Id,fields) => {
		console.log(userId)
		this.props.dispatch({
	        type: 'userCenterUser/add_lfb',
	        payload: {
	        	...fields,
	        	userId:userId,
	        },
	        callback: (res,resMsg) => {
	      	if(res==1){
	      		message.success(resMsg);
	      	}else{
	      		message.error(resMsg);
	      	}
	      },
	    });
	    this.setState({
	      modalVisible: false,
	    });
	};
  
  /*删除*/
 	confirmModel=(title,Id)=>{
 		const { dispatch } = this.props;
		const { selectedRows } = this.state;
    if(Id==undefined&&Object.keys(selectedRows).length==0){
    	message.info("还未选择项");
    }else{
    	var Ids=[];
	    if(Id!=undefined){
	    	Ids=Id;
	    }else if(selectedRows!=null){
	    	Ids.push(selectedRows.map(row => row.userId).join(','));
	    }
	    if(title!="删除"){
	    	var state;
	    	if(title=="禁用"){
	    		state=1;
	    	}else{
	    		state=0;
	    	}
	    	Modal.confirm({
					title: '是否'+title+'选中项状态?',
					okText: '确定',
					cancelText: '取消',
					onOk() {
						/*批量修改状态*/
						dispatch({
							type: 'basics/edit_user_state',
							payload: {
								userIds: Ids,
								state:state,
							},
							callback: (res, resMsg) => {
								if(res == 1) { 
									message.success(resMsg);
								} else { 
									message.error(resMsg);
								}
							},
						});
					}
				});
	    }else{
	    		Modal.confirm({
				    title: '是否删除当前数据选中',
				    content: '',
				    onOk() {
				      dispatch({
					      type: 'userCenterUser/remove_user',
					      payload: {userIds:Ids,},
					      callback: (res,resMsg) => {
					      	if(res==1){
					      		message.success(resMsg);
					      	}else{
					      		message.error(resMsg);
					      	}
					      },
					  	});
				    },
				});
	    }
	  }
 	}
	renderSimpleForm() {
	    const { getFieldDecorator } = this.props.form;
	    return (
	      	<Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
           <Col md={8} sm={24}>
            <FormItem label="用户名">
              {getFieldDecorator('name')(
                <Input placeholder="请输入" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="联系电话">
              {getFieldDecorator('phone')(
                <Input placeholder="请输入" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="地址">
              {getFieldDecorator('address')(
                <Input placeholder="请输入" />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
        {/* <Col md={8} sm={24}>
            <FormItem label="注册时间">
              {getFieldDecorator('createDate')(
                <Input placeholder="请输入" />
              )}
            </FormItem>
          </Col>*/}
           <Col md={8} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('state')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="1">有效</Option>
                  <Option value="0">无效</Option>
                </Select>
              )}
            </FormItem>
          </Col>
           <Col md={16} sm={24}>
            <FormItem>
	            <span style={{ float: 'right', marginBottom: 24 }}>
	           		<Button type="primary" htmlType="submit">查询</Button>
	           		<Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
	            </span>
            </FormItem>
          </Col>
        </Row>
      </Form>
	  );
	}
	render() {
	    const { userCenterUser: { data },loading,threeMenu} = this.props;
	    const { selectedRows, modalVisible,title,obj } = this.state;
		const columns = [{
		 	title: '序号',
		 	dataIndex: 'userId',
		 	key: 'userId',
		 	width: '70px',
		 	render: (text, record, index) => {
		 		return index + 1
		 	}
		 }, {
		 	title: '用户名',
		 	dataIndex: 'name',
		 	key: 'name',
		 	width: '150px',
		 }, {
		 	title: '联系电话',
		 	dataIndex: 'phone',
		 	key: 'phone',
		 	width: '150px',
		 }, {
		 	title: '地址',
		 	dataIndex: 'address',
		 	key: 'address',
		 	width: '250px',
		 }, {
		 	title: '注册时间',
		 	dataIndex: 'createDate',
		 	key: 'createDate',
		 	width: '150px',
		 	render: val => <span>{moment(val).format('YYYY-MM-DD')}</span>,
		 }, {
		 	title: '立方币',
		 	dataIndex: 'lfb',
		 	key: 'lfb',
		 	width: '100px',
		 }, {
		 	title: '积分',
		 	dataIndex: 'point',
		 	key: 'point',
		 	width: '100px',
		 }];
		const columnss = [{
		 	title: '序号',
		 	dataIndex: 'userId',
		 	key: 'userId',
		 	width: '70px',
		 	render: (text, record, index) => {
		 		return index + 1
		 	}
		}, {
		 	title: '用户名',
		 	dataIndex: 'name',
		 	key: 'name',
		 	width: '150px',
		}, {
		 	title: '联系电话',
		 	dataIndex: 'phone',
		 	key: 'phone',
		 	width: '150px',
		}, {
		 	title: '地址',
		 	dataIndex: 'address',
		 	key: 'address',
		 	width: '250px',
		}, {
			title: '注册时间',
		 	dataIndex: 'createDate',
		 	key: 'createDate',
		 	width: '150px',
		 	render: val => <span>{moment(val).format('YYYY-MM-DD')}</span>,
		}, {
		 	title: '立方币',
		 	dataIndex: 'lfb',
		 	key: 'lfb',
		 	width: '100px',
		}, {
		 	title: '积分',
		 	dataIndex: 'point',
		 	key: 'point',
		 	width: '100px',
		}, {
		 	title: '操作',
		    width:'120px',
		    render: (text, record, index) =>{
	    		return <div>
					<a href="javascript:;" onClick={() => this.handleModalVisible(true,record,'添加立方币')}>添加立方币</a>
		    	</div>
		    	
		    }
		}];
		var roleId=sessionStorage.getItem('roleId');
        if(roleId==41||roleId=="41"){
        	var column=columnss
        }else{
        	var column=columns
        }
	    const parentMethods = {
	      	handleAdd: this.handleAdd,
	      	handleModalVisible: this.handleModalVisible,
	      	confirmModel:this.confirmModel,
	    };
	    return (
	    	<PageHeaderLayout title="用户系统/用户管理">
	      <Card bordered={false}>
	        
	          <div className={styles.tableList}>
	            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
	            {/*<span> 
	            	{!threeMenu.new && <Button type="primary" onClick={() => this.handleModalVisible(true,'','新建')} style={{ marginLeft: 8 }}>新建</Button>}
	            	{!threeMenu.edit && <Button type="primary" onClick={() => this.handleModalVisible(true,'','编辑')} style={{ marginLeft: 8 }}>编辑</Button>}
	            	{!threeMenu.delete && <Button type="primary" onClick={() => this.confirmModel('删除')} style={{ marginLeft: 8 }}>删除</Button>}
	            	{!threeMenu.enable && <Button type="primary"  onClick={() => this.confirmModel('启用')}  style={{ marginLeft: 8 }}>启用</Button>}
					      {!threeMenu.enable && <Button  type="ghost"  onClick={() => this.confirmModel('禁用')}  style={{ marginLeft: 8 }}>禁用</Button>}
	            </span>*/}
	            <StandardTable
	              selectedRows={selectedRows}
	              loading={loading}
	              data={data}
	              columns={column}
	              onSelectRow={this.handleSelectRows}
	              onChange={this.handleStandardTableChange}
	              
	            />
	          </div>
	         
	        <CreateForm {...parentMethods} modalVisible={modalVisible} title={title} obj={obj}/>
	      </Card>
	       </PageHeaderLayout>
	    );
	}
}
